# Verify conditions
if [ ! -z $UID ] && [ $UID -ne 0 ]; then
    echo Superuser privileges are required to run this script.
    exit 1
fi

ping -c 1 -W 1 8.8.8.8 > /dev/null 2>&1
if [ $? -ne 0 ]; then
    ping -c 1 -W 1 www.baidu.com > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        echo Network unreachable.
        exit 1
    fi
fi

# Remove files of legacy installation
if [ -d "/opt/dotnet" ]; then
    rm -rf /opt/dotnet
    echo /opt/dotnet removed.
fi

if [ ! -z `cat /etc/environment | grep DOTNET_ROOT=` ]; then
    sed -i '/^DOTNET_ROOT=/d' /etc/environment
    echo /etc/environment reverted.
fi

if [ -f "/etc/profile.d/dotnet-core.sh" ]; then
    rm -f /etc/profile.d/dotnet-core.sh
    echo /etc/profile.d/dotnet-core.sh removed.
fi

if [ -f "/etc/profile.d/dotnet.sh" ]; then
    rm -f /etc/profile.d/dotnet.sh
    echo /etc/profile.d/dotnet.sh removed.
fi

# Remove install lock
rm -f /var/lib/apt/lists/lock
rm -f /var/lib/dpkg/lock
rm -f /var/lib/dpkg/lock-frontend
rm -f /var/cache/apt/archives/lock

# Install .net SDK
mkdir -p /tmp
wget https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.deb -O /tmp/packages-microsoft-prod.deb
dpkg -i /tmp/packages-microsoft-prod.deb
rm /tmp/packages-microsoft-prod.deb

mkdir -p /etc/apt/preferences.d
echo $'Package: *\nPin: origin \"packages.microsoft.com\"\nPin-Priority: 1001' > /etc/apt/preferences.d/99microsoft-dotnet.pref

apt-get update

apt-get install -y dotnet-sdk-3.1=3.1.401-1
apt-get install -y dotnet-sdk-6.0=6.0.300-1
apt-get install -y dotnet-sdk-8.0=8.0.203-1

# Install other software and tools
apt-get install -y glade dos2unix git unrar make libsqlite3-0 libwebkit2gtk-4.0-37 ffmpeg g++ libtinfo5 mesa-utils va-driver-all vdpau-driver-all libmfx1

# Install VSCode
if [ ! -f "/usr/share/code/bin/code" ]; then
    VSCODE_PACKAGE=code_1.70.2-1660629410_amd64.deb
    if [ ! -f $VSCODE_PACKAGE ]; then
        echo $VSCODE_PACKAGE not found.
        exit 1
    fi

    dpkg -i $VSCODE_PACKAGE
    apt-get install -yf
fi

# Install XTools
if [ ! -d "/opt/x-tools" ]; then
    XTOOLS_PACKAGE=20211022_XTools4_X86Linux.rar
    if [ ! -f $XTOOLS_PACKAGE ]; then
        echo $XTOOLS_PACKAGE not found.
        exit 1
    fi

    unrar x ./$XTOOLS_PACKAGE /opt/
fi

echo Done.
